// pages/public/article_detail/article_detail.js
const app = getApp()
import {
    _get,
    _post,
    _headerGet,
    _headerPost,
    config
} from '../../../utils/httpUtils.js'
const RSA = require("../../../utils/wx_rsa.js");

Page({
    data: {
        ip: config.host,
        navbarData: {
            showCapsule: 1, //是否显示左上角图标
            title: '' //导航栏 中间的标题
        },
        height: app.globalData.height,
        id: '',
        showComment: true,
        purchase: false,
        buyBtn: '',
        buyNumber: 1, //默认商品数量
        maskSty: "none",
        showTop: true,
        html: [],
        commentWidth: 330,
        articleHeight: 800,
        animationData: "",
        goods: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(option) {
        if (option.scene) {
            let scene = option.scene.split('--'); // 通过二维码扫码进来的参数
            scene[0] == 1 ? this.getDetail(scene[1]) : wx.redirectTo({
                url: `/pages/activity/line001/detail?id=${scene[1]}&uid=${scene[2]}`
            })
        } else {
            this.getGoodsAttr(option.id)
            this.data.id = option.id //储存文章 id
        }
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        let _this = this;
        wx.createSelectorQuery().select(`.article`).boundingClientRect(function(rect) {
            if (rect.height < 800) {
                _this.setData({
                    showAllHide: true
                })
            }
        }).exec()
    },
    pageScrollToBottom: function(e) { //页面滚动
        wx.createSelectorQuery().select(`.${e.currentTarget.dataset.position}`).boundingClientRect(function(rect) {
            if (rect.height < 667) return
            wx.pageScrollTo({
                scrollTop: rect.height,
                duration: 500
            })
        }).exec()
    },
    getGoodsAttr(id) { //获取商品详情
        _post('/api/goods/get_goods_detail', {
            'id': id,
            'v': '1.1.0'
        }, res => {
            if (res.data.code == 1) {
                wx.stopPullDownRefresh()
                this.setData({
                    goods: res.data.data,
                    purchase: true,
                    html: res.data.data.goodsImgs
                })
                let detail = res.data.data.goodsDetail;
                if (detail.g_spec_format != '') {
                    let child = JSON.parse(detail.g_spec_format)
                    let defChioce = ''
                    //设置属性的状态，并默认选中第一个
                    for (let i = 0; i < child.length; i++) {
                        for (let j = 0; j < child[i].spec_value.length; j++) {
                            if (j == 0) {
                                child[i].spec_value[j].active = true
                                defChioce = defChioce + child[i].spec_id + ':' + child[i].spec_value[j].spec_value_id + ';';
                            } else {
                                child[i].spec_value[j].active = false
                            }
                        }
                    }
                    this.defaultType(defChioce) //设置默认选项
                    this.setData({
                        g_spec_format: child,
                    })
                }
            } else {
                wx.stopPullDownRefresh()
                wx.showToast({
                    title: res.data.msg,
                    duration: 2000,
                    icon: 'none'
                })
            }
        })
    },
    defaultType(choice) { //根据结果判断判断商品类型
        let skuArr = this.data.goods.goodsSku
        for (let k = 0; k < skuArr.length; k++) {
            if (skuArr[k].attr_value_items == choice.substring(0, choice.length - 1)) {
                this.setData({
                    goodsType: skuArr[k]
                })
            }
        }
    },
    labelItemTap(e) {
        // 取消该分类下的子栏目所有的选中状态
        let childs = this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value;
        for (let i = 0; i < childs.length; i++) {
            this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value[i].active = false;
        }
        // 设置当前选中状态
        this.data.g_spec_format[e.currentTarget.dataset.propertyindex].spec_value[e.currentTarget.dataset.propertychildindex].active = true;
        //获取所有的选中规格尺寸数据
        let needSelectNum = this.data.g_spec_format.length;
        let curSelectNum = 0;
        let propertyChildIds = "";
        let propertyChildNames = "";
        //得到选中结果
        for (let i = 0; i < this.data.g_spec_format.length; i++) {
            let childs = this.data.g_spec_format[i].spec_value;
            for (let j = 0; j < childs.length; j++) {
                if (childs[j].active) {
                    curSelectNum++;
                    propertyChildIds = propertyChildIds + this.data.g_spec_format[i].spec_id + ":" + childs[j].spec_value_id + ";"
                    propertyChildNames = propertyChildNames + childs[j].spec_name + ":" + childs[j].spec_value_name + ";"
                }
            }
        }
        //根据结果判断判断商品类型
        let skuArr = this.data.goods.goodsSku
        for (let k = 0; k < skuArr.length; k++) {
            if (skuArr[k].attr_value_items == propertyChildIds.substring(0, propertyChildIds.length - 1)) {
                this.setData({
                    goodsType: skuArr[k]
                })
            }
        }
        this.setData({
            g_spec_format: this.data.g_spec_format
        })
    },
    //数量减少
    numJianTap: function() {
        if (this.data.buyNumber > 1) {
            let currentNum = this.data.buyNumber;
            currentNum--;
            this.setData({
                buyNumber: currentNum
            })
        }
    },
    //数量增加
    numJiaTap: function() {
        if (this.data.buyNumber < this.data.goods.goodsDetail.goods_stock) {
            let currentNum = this.data.buyNumber;
            currentNum++
            this.setData({
                buyNumber: currentNum
            })
        }
    },

    buyNow() { // 立即购买
        if (this.data.goodsType.stock == 0) {
            wx.showToast({
                title: '库存不足哦',
                icon: 'none'
            })
            return
        }
        let _data = {
            c_client: 'weixinSmall',
            type: 'buyNow',
            skuId: this.data.goodsType.sku_id,
            num: this.data.buyNumber,
            v: '1.1.0'
        }
        wx.navigateTo({
            url: '/pages/public/confirm-order/index?data=' + JSON.stringify(_data)
        })
    },

    joinCart() { // 加购
        if (this.data.goodsType.stock == 0) {
            wx.showToast({
                title: '库存不足哦',
                icon: 'none'
            })
            return
        }
        let _data = {
            c_client: 'weixinSmall',
            g_id: this.data.id,
            sku_id: this.data.goodsType.sku_id,
            num: this.data.buyNumber,
            v: '1.1.0'
        }
        let that = this; //更改 this 指向
        _headerPost('/api/Cart/addCart', _data, res => {
            wx.showToast({
                title: res.data.msg,
                duration: 2000,
                icon: 'none',
                success() {
                    that.closePopupTap()
                }
            })
        })
    },
    cart() { // 购物车
        wx.navigateTo({
            url: '/pages/shop-cart/index',
        })
    },

    handOver(event) { // 获取属性
        let currentId = event.currentTarget.dataset.id;
        this.setData({
            cate_id: currentId,
        })
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        this.getGoodsAttr(this.data.id)
    },

    _navback() { //返回
        wx.navigateBack()
    },

    closePopupTap() {
        this.setData({
            maskSty: 'none'
        })
    },

    showPopupTap() {
        this.setData({
            maskSty: 'block'
        })
    },

    previewImage(e) {
        let currentSrc = e.currentTarget.dataset.src;
        let currentSrcArray = e.currentTarget.dataset.srcarr;
        wx.previewImage({
            current: currentSrc, // 当前显示图片的http链接
            urls: [currentSrcArray] // 需要预览的图片http链接列表
        })
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },
    showBuyBtn() {
        this.commentFocus()
    },

    commentFocus(e) { //键盘聚焦
        this.setData({
            showComment: false,
            commentWidth: 530,
            buyBtn: true
        })
    },

    commentBlur(e) { //键盘失去焦点
        this.setData({
            showComment: true,
            commentWidth: 330,
            buyBtn: ''
        })
    },
    showAll() {
        let _hei = this.data.articleHeight
        if (_hei >= 800) {
            this.setData({
                articleHeight: 'auto'
            })
        } else {
            this.setData({
                articleHeight: '800'
            })
        }
    },

    onPageScroll: function(e) { // 滚动监听返回顶部按钮
        if (e.scrollTop >= 1000) {
            this.setData({
                showTop: false
            })
        } else if (e.scrollTop < 1000) {
            this.setData({
                showTop: true
            })
        }
    },

    scrollTop() {
        wx.pageScrollTo({
            scrollTop: 0,
            duration: 500
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        return {
            title: `${this.data.goods.goodsDetail.goods_name}`,
            imageUrl: `${this.data.goods.goodsDetail.goods_photo}`,
        }
    }
})